<?php
/**
 * （Logic）
 */
namespace App\Logic\Amazon;
use App\Libs\MWSFinancesService\FinancesMws;
use App\Libs\RequestClient;

class GrabFinances extends GrabCommon
{
    const GRAB_FINANCES_START = '-15 day';
    const GRAB_FINANCES_INTERVAL = 86400 * 15;

    /**
     * 返回给定日期范围的财务事件组。
     * API ListFinancialEventGroups
     * @param array $con
     */
    public static function listFinancialEventGroups($con = array()){
        if(!isset($con['account'])||!isset($con['account']['id']))die(0);
        $account = $con['account'];
        self::_matchListFinancialEventGroupsCondition($con,$account);
        $service = self::getRequestClient('finances',$account);
        $fm = FinancesMws::getInit();
        $param = $fm->ListFinancialEventGroups($con);
        $data = $service->requestExe($param);
        $nextToken = self::_extractListFinancialEventGroupsResponse($account,$data);
        self::_listFinancialEventGroupsByNextToken($account,$service,$nextToken);

    }

    /**
     * 返回给定日期范围的下一页财务事件组。
     * API ListFinancialEventGroupsByNextToken
     * @param $account
     * @param $service
     * @param $nextToken
     */
    private static function _listFinancialEventGroupsByNextToken($account,$service,$nextToken){
        if(!$nextToken)die(0);
        if(!($service instanceof RequestClient)){
            $service = self::getRequestClient('finances',$account);
        }
        $fm = FinancesMws::getInit();
        $param = $fm->listFinancialEventGroupsByNextToken(['SellerId'=>$account['merchant'],'NextToken'=>$nextToken,'MWSAuthToken' => $account['mws_auth_token']]);
        $data = $service->requestExe($param);
        $nextToken = self::_extractListFinancialEventGroupsResponse($account,$data,true);
        self::_listFinancialEventGroupsByNextToken($account,$service,$nextToken);
    }

    private static function _extractListFinancialEventGroupsResponse($account,$data,$flag=false){
        $_str = $flag?'ListFinancialEventGroupsByNextTokenResult':'ListFinancialEventGroupsResult';
        $response = ['Account'=>$account];
        $response['FinancialEventGroupList'] = isset($data[$_str]['FinancialEventGroupList'])?$data[$_str]['FinancialEventGroupList']:[];
        //TODO
        //处理$response
        return isset($data[$_str]['NextToken'])?$data[$_str]['NextToken']:null;
    }

    /**
     * 匹配ListFinancialEventGroups参数
     * @param $con
     * @param $account
     */
    private static function _matchListFinancialEventGroupsCondition(&$con,$account){
        $con['FinancialEventGroupStartedAfter'] = getDateFormat(strtotime(isset($con['financialEventGroupStartedAfter'])?$con['financialEventGroupStartedAfter']:date('Ymd',strtotime(self::GRAB_FINANCES_START))));
        $con['FinancialEventGroupStartedBefore'] = getDateFormat(isset($con['financialEventGroupStartedBefore'])?strtotime($con['financialEventGroupStartedBefore']):strtotime($con['FinancialEventGroupStartedAfter'])+self::GRAB_FINANCES_INTERVAL);
        $con['SellerId'] = $account['merchant'];
        $con['MWSAuthToken'] = $account['mws_auth_token'];
    }

    /**
     * 返回给定订单，财务事件组或日期范围的财务事件。
     * API ListFinancialEvents
     * @param array $con
     */
    public static function listFinancialEvents($con = array()){
        if(!isset($con['account'])||!isset($con['account']['id']))die(0);
        $account = $con['account'];
        self::_matchListFinancialEventsCondition($con,$account);
        $service = self::getRequestClient('finances',$account);
        $fm = FinancesMws::getInit();
        $param = $fm->listFinancialEvents($con);
        $data = $service->requestExe($param);
        $nextToken = self::_extractListFinancialEventsResponse($account,$data);
        self::_listListFinancialEventsByNextToken($account,$service,$nextToken);
    }

    /**
     * 返回给定日期范围的下一页财务事件组。
     * API ListFinancialEventsByNextToken
     * @param $account
     * @param $service
     * @param $nextToken
     */
    private static function _listListFinancialEventsByNextToken($account,$service,$nextToken){
        if(!$nextToken)die(0);
        if(!($service instanceof RequestClient)){
            $service = self::getRequestClient('finances',$account);
        }
        $fm = FinancesMws::getInit();
        $param = $fm->listFinancialEventsByNextToken(['SellerId'=>$account['merchant'],'NextToken'=>$nextToken,'MWSAuthToken' => $account['mws_auth_token']]);
        $data = $service->requestExe($param);
        $nextToken = self::_extractListFinancialEventsResponse($account,$data,true);
        self::_listListFinancialEventsByNextToken($account,$service,$nextToken);
    }

    private static function _extractListFinancialEventsResponse($account,$data,$flag=false){
        $_str = $flag?'ListFinancialEventsByNextTokenResult':'ListFinancialEventsResult';
        $response = ['Account'=>$account];
        $response['FinancialEvents'] = isset($data[$_str]['FinancialEvents'])?$data[$_str]['FinancialEvents']:[];
        //TODO
        //处理$response
        return isset($data[$_str]['NextToken'])?$data[$_str]['NextToken']:null;
    }

    /**
     * 匹配ListFinancialEvents参数
     * @param $con
     * @param $account
     */
    private static function _matchListFinancialEventsCondition(&$con,$account){
        $flag = self::_checkCondition($con);
        switch ($flag)
        {
            case 1:
                $con['AmazonOrderId'] = $con['amazonOrderId'];break;
            case 2:
                $con['FinancialEventGroupId'] = $con['financialEventGroupId'];break;
            default:
                $con['PostedAfter'] = getDateFormat(strtotime(isset($con['postedAfter'])?$con['postedAfter']:date('Ymd',strtotime(self::GRAB_FINANCES_START))));
                $con['PostedBefore'] = getDateFormat(isset($con['postedBefore'])?strtotime($con['postedBefore']):strtotime($con['PostedAfter'])+self::GRAB_FINANCES_INTERVAL);
        }
        $con['SellerId'] = $account['merchant'];
        $con['MWSAuthToken'] = $account['mws_auth_token'];
    }

    private static function _checkCondition($con){
        if(isset($con['amazonOrderId'])&&$con['amazonOrderId']){
            return 1;
        }elseif(isset($con['financialEventGroupId'])&&$con['financialEventGroupId']){
            return 2;
        }else{
            return 3;
        }
    }

}
